package com.example.Arithmetic.Arithmetic;

import java.util.LinkedList;

/**
 * 日期：2023/10/14
 * 时间：20:18
 * 描述：解析运算公式为计算机所操作的运算公式
 * 中缀表达式转后缀
 */

public class InfixToSuffix {

    public String InfixToSuffix(String msg) {
        StringBuilder stringBuilder = new StringBuilder(msg.length());
        LinkedList<Character> list = new LinkedList();
        for (int i = 0; i < msg.length(); i++) {
            char c = msg.charAt(i);
            switch (c) {
                case '+', '-', '*', '/' -> {
//                    两种情况，如果栈为空
                    if (list.isEmpty()) {
                        list.push(c);
//                        不为空情况
                    } else {
//                        运算优先级高
                        if (prioprty(c) > prioprty(list.peek())) {
                            list.push(c);
                        } else {
                            while (!list.isEmpty() && prioprty(list.peek()) >= prioprty(c)) {
                                stringBuilder.append(list.pop());
                            }
                            stringBuilder.append(c);
                        }

                    }
                }
                case '(' -> {
                    list.push(c);
                }
                case ')' -> {
                    while (!list.isEmpty() && list.peek() != '(') {
                        stringBuilder.append(list.pop());
                    }
                    list.pop();
                }
                default -> {
                    stringBuilder.append(c);
                }
            }
        }
        while (!list.isEmpty()) {
            stringBuilder.append(list.pop());
        }
        return stringBuilder.toString();
    }

    public int prioprty(char ms) {
        return switch (ms) {
            case '+', '-' -> 1;
            case '*', '/' -> 2;
            case '(' -> 0;
            default -> throw new IllegalArgumentException("参数错误");
        };
    }
}
